package pl.kaczmarz.audiosteganography;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.JTextComponent;

/**
 *
 * @author Pawel
 */
public class FileChooser extends JPanel {
	private JTextField textField;
	private JButton button;
	private JFileChooser fc;
	private FileChooserListener fcl;

	public FileChooser(int mode, String caption, String buttonCaption) {
		textField = new JTextField(30);
		button = new JButton(buttonCaption);

		setLayout(new BorderLayout());

		add(button, BorderLayout.EAST);
		add(textField, BorderLayout.CENTER);

		setBorder(BorderFactory.createTitledBorder(caption));

		fc = new JFileChooser();
		fcl = new FileChooserListener(mode, fc, this, textField);

		button.addActionListener(fcl);
	}

	public String getFileName() {
		return textField.getText().trim();
	}

	public void setFileName(String fileName) {
		this.textField.setText(fileName);
	}

	public void setMode(int mode) {
		fcl.setMode(mode);
	}

	public void setFileFilter(String description, String... extensions) {
		fc.setFileFilter(new FileNameExtensionFilter(description, extensions));
	}


	private class FileChooserListener implements ActionListener {

		private Component parent;
		private JTextComponent text;
		private int mode;
		private JFileChooser fc;

		public FileChooserListener(int mode, JFileChooser fc, Component parent, JTextComponent text) {
			this.parent = parent;
			this.text = text;
			this.mode = mode;
			this.fc = fc;
		}

		public void setMode(int mode) {
			this.mode = mode;
		}

		@Override
		public void actionPerformed(ActionEvent ae) {

			int choice = JFileChooser.ERROR_OPTION;

			switch (mode) {
				case JFileChooser.OPEN_DIALOG:
					choice = fc.showOpenDialog(this.parent);
					break;
				case JFileChooser.SAVE_DIALOG:
					choice = fc.showSaveDialog(this.parent);
					break;
			}

			if (choice == JFileChooser.APPROVE_OPTION) {

				File file = fc.getSelectedFile();

				if (file != null && text != null) {
					this.text.setText(file.getPath());
				}
			}
		}
	}
}
